package com.wzl.mixed.controller;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 失效服务地址本地缓存
 *
 * @author weizhongli
 * @since 1.0, 2023/02/10 15:05
 */
@Slf4j
public class AidubboExtirpationCache {

    /**
     * 默认缓存时长 单位s
     */
    private static final int DEFAULT_TIMEOUT = 3600;
    /**
     * 默认缓存容量
     */
    private static final int DEFAULT_SIZE = 1000;

    /**
     * 存储数据
     */
    private static final Map<String,Object> data;

    private static final ScheduledExecutorService executorService;

    /**
     * Dubbo服务失效地址缓存
     */
    //初始化数据
    static {
        data = new ConcurrentHashMap<>(DEFAULT_SIZE);
        executorService = new ScheduledThreadPoolExecutor(2);
    }

    /**
     * 私有化构造函数
     */
    private AidubboExtirpationCache(){}

    //静态内部类
    static class CacheCleanTask extends TimerTask {

        private String key;

        private CacheCleanTask(String key){
            this.key = key;
        }

        public static CacheCleanTask cacheTask(String key){
            return  new CacheCleanTask(key);
        }

        @Override
        public void run() {
            //移除对应 key
            AidubboExtirpationCache.remove(key);
        }
    }

    /**
     * 增加缓存 默认有效时长
     * @param key
     * @param value
     */
    public static void put(String key, Object value){
        data.put(key,value);
        //定时器 调度任务，用于根据 时间 定时清除 对应key 缓存
        executorService.schedule(new TimerTask() {
            @Override
            public void run() {
                remove(key);
            }
        }, DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    }

    /**
     * 增加缓存  并设置缓存时长 单位 s
     * @param key
     * @param value
     * @param timeout 缓存时长 单位s
     */
    public static void put(String key, Object value, int timeout){
        data.put(key, value);
        //lambda 替换匿名内部类
        executorService.schedule(() -> remove(key), timeout, TimeUnit.SECONDS);
    }

    /**
     * 获取缓存
     * @param key
     * @return
     */
    public static Object get(String key){
        return data.get(key);
    }

    /**
     * 获取当前缓存中 所有的key
     * @return
     */
    public static Set<String> cacheKeys(){
        return data.keySet();
    }

    /**
     * 删除缓存
     * @param key
     */
    public static void remove(String key){
        data.remove(key);
    }

//    /**
//     * 清空所有缓存
//     */
//    public static void clear(){
//        if(size() > 0){
//            data.clear();
//        }
//    }

}